#include "ConfigMgr.h"
#include <fstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <iostream>

SectionInfo::SectionInfo()
{
}

std::string SectionInfo::operator[](const std::string &key)
{
    if (_vals.find(key) == _vals.end())
        return "this is an empty str";
    return _vals[key];
}

void SectionInfo::set_vals(std::map<std::string, std::string> vals)
{
    this->_vals = vals;
}

SectionInfo ConfigMgr::operator[](const std::string &section)
{
    if (_sections.find(section) == _sections.end())
    {
        std::cout << "cannot find: " << section << std::endl;
        return SectionInfo();
    }
    return _sections[section];
}

ConfigMgr &ConfigMgr::Inst()
{
    static ConfigMgr _instance;
    return _instance;
}

ConfigMgr::ConfigMgr()
{
    // 获取当前工作目录
    boost::filesystem::path parent_path = boost::filesystem::current_path().parent_path();
    // 构建config.ini文件的完整路径
    boost::filesystem::path config_path = parent_path / "config" / "config.ini";
    std::cout << "Config path: " << config_path << std::endl;

    // 使用Boost.PropertyTree来读取INI文件
    boost::property_tree::ptree pt;
    boost::property_tree::read_ini(config_path.string(), pt);

    for (const auto &section_pair : pt)
    {
        const std::string &section_name = section_pair.first;
        const boost::property_tree::ptree &section_tree = section_pair.second;

        // 对于每个section，遍历其所有的key-value对
        std::map<std::string, std::string> section_config;
        for (const auto &key_value_pair : section_tree)
        {
            const std::string &key = key_value_pair.first;
            const std::string &value = key_value_pair.second.get_value<std::string>();
            section_config[key] = value;
        }
        SectionInfo sectionInfo;
        sectionInfo.set_vals(section_config);
        // 将section的key-value对保存到_sections中
        _sections[section_name] = sectionInfo;
    }
}
